package com.huluobo.day_1_lifecycledemo.room;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.huluobo.day_1_lifecycledemo.R;
import com.huluobo.day_1_lifecycledemo.databinding.ActivityRoomBinding;
import com.huluobo.day_1_lifecycledemo.viewbinding.BaseActivity;

import java.util.List;

public class RoomActivity extends BaseActivity<ActivityRoomBinding> {
    private AccountDatabase database;

    @Override
    protected ActivityRoomBinding getViewBinding() {
        return ActivityRoomBinding.inflate(getLayoutInflater());
    }


    private Migration migration_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE Account ADD COLUMN _loginAge TEXT");
        }
    };

    private Migration migration_3_4 = new Migration(3, 4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE Account ADD COLUMN _loginAge TEXT");
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //.allowMainThreadQueries()让查询强制运行在主线程当中,演示用的或者考试用,在公司项目中不要这么创建
        //.fallbackToDestructiveMigration()  破坏性的重建数据库,会丢失所有数据,也是升级策略之一
        database =
                Room.databaseBuilder(getApplicationContext(), AccountDatabase.class, "account.db")
//                        .fallbackToDestructiveMigration()
                        .addMigrations(migration_3_4)
                        .allowMainThreadQueries().build();

        viewBinding.btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AccountBean account = database.getAccountDAO().findAccountByLoginName(getLoginAccount());
                if (account != null) {
                    //如果账号已经存在,密码也相同的话不做任何操作,可以登录
                    //如果账号相同,密码不同,则更新密码
                    if (!account.loginPassword.equals(getLoginPassword())) {
                        account.loginPassword = getLoginPassword();
                        database.getAccountDAO().updateAccountBean(account);
                    }
                } else {
                    AccountBean accountBean = new AccountBean(getLoginAccount(), getLoginPassword());
                    database.getAccountDAO().insertAccount(accountBean);
                }
            }
        });
        viewBinding.btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<AccountBean> list = database.getAccountDAO().loadAccountList();
                viewBinding.tvResult.setText("");
                for (int i = 0; i < list.size(); i++) {
                    viewBinding.tvResult.append("账号:" + list.get(i).loginAccount);
                    viewBinding.tvResult.append("密码:" + list.get(i).loginPassword);
                }
            }
        });

        viewBinding.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<AccountBean> list = database.getAccountDAO().loadAccountList();
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).loginAccount.equals(getLoginAccount())) {
                        database.getAccountDAO().deleteAccount(list.get(i));
                    }
                }
            }
        });
    }

    private String getLoginAccount() {
        return viewBinding.edLoginAccount.getText().toString();
    }

    private String getLoginPassword() {
        return viewBinding.edLoginPassword.getText().toString();
    }

    private void closeDb() {
        if (database.isOpen()) {
            database.close();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDb();
    }
}